package com.lujieni.netty.c4;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.CompositeByteBuf;

import static io.netty.buffer.ByteBufUtil.appendPrettyHexDump;
import static io.netty.util.internal.StringUtil.NEWLINE;

public class TestCompositeByteBuf {

    public static void main(String[] args) {

        ByteBuf b1 = ByteBufAllocator.DEFAULT.buffer();
        b1.writeBytes(new byte[]{'a', 'b'});

        ByteBuf b2 = ByteBufAllocator.DEFAULT.buffer();
        b2.writeBytes(new byte[]{'c', 'd'});

        //合并2个ByteBuf
        CompositeByteBuf buf = ByteBufAllocator.DEFAULT.compositeBuffer();
        buf.addComponents(true, b1, b2);
        log(buf);

        // no necessary for releasing buf's memory because b1 and b2 has been released
        b1.release();
        b2.release();
    }

    public static void log(ByteBuf bb){
        int length = bb.readableBytes();
        int rows = length / 16 + (length % 15 == 0 ? 0 : 1 ) + 4;
        StringBuilder sb = new StringBuilder(rows * 80 * 2)
                .append("read index:").append(bb.readerIndex())
                .append(" write index:").append(bb.writerIndex())
                .append(" capacity:").append(bb.capacity())
                .append(NEWLINE);
        appendPrettyHexDump(sb, bb);
        System.out.println(sb.toString());
    }


}
